﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ACH
{
    public partial class TrainingParticipants : Form
    {
        List<RadioButton> rooms;
        public TrainingParticipants()
        {
            InitializeComponent();
        }

        private void toolStripSave_Click(object sender, EventArgs e)
        {
            this.Validate();
            bindingSource1.EndEdit();
            trainingParticipantsTableAdapter.Update(aCHDataSet.TrainingParticipants);
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            trainingParticipantsTableAdapter.Update(aCHDataSet.TrainingParticipants);
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            Helper.CreateNew(bindingSource1);
        }

        private void TrainingParticipants_Load(object sender, EventArgs e)
        {

            //           SELECT CASE WHEN (NOT TPE.Expenses_ID IS NULL) THEN (1) ELSE (0) END Assoc, E.ID, E.[Type], E.Value
            //FROM Expenses E
            //LEFT OUTER JOIN TrainingParticipants_Expenses TPE ON E.ID = TPE.Expenses_ID AND TPE.Trainingparticipant_ID = 'current participant ID'
            //ORDER BY E.[Type] ASC


            // TODO: This line of code loads data into the 'aCHDataSet.TrainingParticipants_Expenses' table. You can move, or remove it, as needed.
            this.trainingParticipants_ExpensesTableAdapter.Fill(this.aCHDataSet.TrainingParticipants_Expenses);
            // TODO: This line of code loads data into the 'aCHDataSet.TrainingParticipantPositions' table. You can move, or remove it, as needed.
            this.trainingParticipantPositionsTableAdapter.Fill(this.aCHDataSet.TrainingParticipantPositions);
            // TODO: This line of code loads data into the 'aCHDataSet.Members' table. You can move, or remove it, as needed.
            this.membersTableAdapter.Fill(this.aCHDataSet.Members);
            // TODO: This line of code loads data into the 'aCHDataSet.TrainingParticipants' table. You can move, or remove it, as needed.
            this.trainingParticipantsTableAdapter.Fill(this.aCHDataSet.TrainingParticipants);

            this.roomOccupanciesRadiosTableAdapter.Fill(this.aCHDataSet.RoomOccupanciesRadios, (bindingSource1.Current as DataRowView)["Training_ID"].ToString());
            this.gridAssocTableAdapter.Fill(this.aCHDataSet.GridAssoc, (bindingSource1.Current as DataRowView)["ID"].ToString());
            FillRadioButtons();
            txtTrainingName.Text = (bindingSource1[bindingSource1.Position] as DataRowView)["Training_Name"].ToString();
            SetAccomodation();
        }

        private void SetAccomodation()
        {
            DataRowView row = bindingSource1[bindingSource1.Position] as DataRowView;
            if (row["Room_ID"] != DBNull.Value)
            {
                rbtnAccomodation.Checked = true;
                dateAccStart.Value = Convert.ToDateTime(row["StartDate"]);
                dateAccEnd.Value = Convert.ToDateTime(row["EndDate"]);
                txtSelectedAccomodation.Text = row["Room_Name"].ToString();
                txtSelectedAccomodation.Tag = row["Room_ID"].ToString();
            }
            else
            {
                rbtnNoAccomodation.Checked = true;
                dateAccStart.Value = dateStart.Value;
                dateAccEnd.Value = dateEnd.Value;
                txtSelectedAccomodation.Text = string.Empty;
                txtSelectedAccomodation.Tag = null;
            }
        }

        private void FillRadioButtons()
        {
            rooms = new List<RadioButton>();
            for (int i = 0; i < aCHDataSet.RoomOccupanciesRadios.Rows.Count; i++)
            {
                RadioButton b = new RadioButton();
                b.Name = aCHDataSet.RoomOccupanciesRadios.Rows[i]["Room"].ToString();
                RoomOccupancy ro = new RoomOccupancy(aCHDataSet.RoomOccupanciesRadios.Rows[i]["ID"].ToString(), (int)aCHDataSet.RoomOccupanciesRadios.Rows[i]["Total"],
                    (int)aCHDataSet.RoomOccupanciesRadios.Rows[i]["Available"], aCHDataSet.RoomOccupanciesRadios.Rows[i]["Room"].ToString());
                b.Tag = ro;
                b.Text = ro.RoomName + "   -   " + ro.AvailablePlaces.ToString() + "/" + ro.TotalPlaces.ToString();
                b.Location = new Point(i * 2, 15);
                b.AutoSize = true;
                if (ro.AvailablePlaces == 0)
                    b.Enabled = false;
                if ((bindingSource1.Current as DataRowView).Row["Room_ID"] as string == ro.LodgingRoomID)
                {
                    b.Checked = true;
                    b.Enabled = true;
                }

                b.CheckedChanged += new EventHandler(b_CheckedChanged);
                rooms.Add(b);
                flowLayoutPanel1.Controls.Add(b);
            }
        }

        void b_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton r = sender as RadioButton;
            if (r.Checked)
                AddNewLink(r);
            else
                RemoveLink(r);
        }

        private void RemoveLink(RadioButton r)
        {
            RoomOccupancy ro = r.Tag as RoomOccupancy;

        }

        private void AddNewLink(RadioButton r)
        {
            throw new NotImplementedException();
        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            ;
        }

        private void grdExpenses_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((bool)grdExpenses[e.ColumnIndex, e.RowIndex].EditedFormattedValue)
                DeleteParticipantExpense((bindingSource1[bindingSource1.Position] as DataRowView)["ID"].ToString(),
                    grdExpenses[1, e.RowIndex].Value.ToString());
            else
                CreateParticipantExpense((bindingSource1[bindingSource1.Position] as DataRowView)["ID"].ToString(),
                     grdExpenses[1, e.RowIndex].Value.ToString());
        }

        private void CreateParticipantExpense(string participant_ID, string expense_ID)
        {
            DataRowView newRow = assocBindingSource.AddNew() as DataRowView;
            newRow.Row["ID"] = Guid.NewGuid();
            newRow.Row["TrainingParticipant_ID"] = participant_ID;
            newRow.Row["Expense_ID"] = expense_ID;
            newRow.Row["CreateDate"] = DateTime.Now;
            newRow.Row["UpdateDate"] = DateTime.Now;
            newRow.Row["UpdateUser"] = "????";
            newRow.Row["CreateUser"] = "????";
            assocBindingSource.EndEdit();
            trainingParticipants_ExpensesTableAdapter.Update(aCHDataSet.TrainingParticipants_Expenses);
        }

        private void DeleteParticipantExpense(string participant_ID, string expense_ID)
        {
            assocBindingSource.Filter = "TrainingParticipant_ID = '" + participant_ID + "' AND Expense_ID = '" + expense_ID + "'";
            if (assocBindingSource.Count != 1)
                return;
            (assocBindingSource[0] as DataRowView).Delete();
            trainingParticipants_ExpensesTableAdapter.Update(aCHDataSet.TrainingParticipants_Expenses);
        }

        private void bindingSource1_CurrentChanged(object sender, EventArgs e)
        {
            ;
        }

        private void bindingSource1_CurrentItemChanged(object sender, EventArgs e)
        {
            ;
        }

        private void rbtnAccomodation_CheckedChanged(object sender, EventArgs e)
        {
            grpAccomodation.Enabled = rbtnAccomodation.Checked;
            if (rbtnAccomodation.Checked)
            {
                dateAccStart.Value = dateStart.Value;
                dateAccEnd.Value = dateEnd.Value;
            }
        }

        private void btnAccSearch_Click(object sender, EventArgs e)
        {
            string sql = "SELECT rt.NoOfBeds - COUNT(tro.LodgingRoom_ID) AS available, rt.NoOfBeds AS total, lr.ID, lr.Name AS Room " +
"FROM   (SELECT _tp.ID, _tp.Member_ID FROM TrainingParticipants AS _tp INNER JOIN Trainings AS t ON _tp.Training_ID = t.ID " +
"WHERE (t.ID = @Training_ID)) AS tp INNER JOIN Members AS m ON tp.Member_ID = m.ID INNER JOIN TrainingRoomOccupancies AS tro ON tro.TrainingParticipant_ID = tp.ID " +
"RIGHT OUTER JOIN LodgingRooms AS lr ON tro.LodgingRoom_ID = lr.ID INNER JOIN RoomTypes AS rt ON rt.ID = lr.RoomType_ID " +
"GROUP BY lr.Name, lr.ID, rt.NoOfBeds ORDER BY Room";
            SqlParameter param = new SqlParameter("@Training_ID", (bindingSource1[bindingSource1.Position] as DataRowView)["Training_ID"].ToString());
            DataTable dt = Helper.ExecuteSql(sql, new SqlParameter[] { param });
            ChooseAccomodation ca = new ChooseAccomodation(dt, txtSelectedAccomodation.Tag.ToString());
            if (ca.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ;//not done
            }
        }


        //trainingsBindingSource.Filter = "ID = '" + (bindingSource1.Current as DataRowView)["Training_ID"].ToString() + "'";

    }

    public class RoomOccupancy
    {
        private string _lodgingRoomID;
        private int _totalPlaces;
        private int _availablePlaces;
        private string _roomName;

        public string LodgingRoomID
        {
            get { return _lodgingRoomID; }
        }

        public int TotalPlaces
        { get { return _totalPlaces; } }

        public int AvailablePlaces
        { get { return _availablePlaces; } }

        public string RoomName
        { get { return _roomName; } }

        public RoomOccupancy(string lodgingRoomID, int totalPlaces, int availablePlaces, string roomName)
        {
            _lodgingRoomID = lodgingRoomID;
            _totalPlaces = totalPlaces;
            _availablePlaces = availablePlaces;
            _roomName = roomName;
        }
    }
}
